from research.calcor import calcor_base
class nhnl_r_fx(calcor_base):
    def __init__(self, timeperiod=250, mintimeperiod=60, price="close", fx="high"):
        self.timeperiod = timeperiod
        self.mintimeperiod = mintimeperiod
        self.price = price
        self.fx = fx
        self.data = []
        self.timekey = None
    def oncalc(self, b, timekey=None):
        rst = None
        if b is not None:
            timekey = b["timekey"]
            price = b[self.price]
            if not price:
                if self.data:
                    price = self.data[-1]
            if timekey is not None:
                if timekey == self.timekey:
                    self.data[-1] = price
                else:
                    self.data.append(price)
                    self.timekey = timekey
            else:
                self.data.append(price)
            if len(self.data) > self.timeperiod:
                self.data.pop(0)
            if len(self.data) >= self.mintimeperiod:
                if self.fx == "high":
                    p0 = max(self.data)
                    rst = 1 - price / p0
                else:
                    p0 = min(self.data)
                    rst = price / p0 - 1
        return rst
class nhnl_r(calcor_base):
    def __init__(self,timeperiod=250,mintimeperiod=60):
        super().__init__(timeperiod=timeperiod,mintimeperiod=mintimeperiod,datatype="dim1")
    def calc(self):
        p0=max(self.hisdata)
        p1 = min(self.hisdata)
        p2=self.hisdata[-1]
        r0 = (p2 - p1) / p1
        r1 = (p2 - p0) / p0
        return r0, r1
class nhnl_r_bybar(calcor_base):
    def __init__(self, timeperiod=250, mintimeperiod=60):
        super().__init__(timeperiod=timeperiod, mintimeperiod=mintimeperiod, datatype="bar", inputs=["high","low","close"])
    def calc(self):
        p0 = max(self.hisdata["high"])
        p1 = min(self.hisdata["low"])
        p2 = self.hisdata["close"][-1]
        r0 = (p2-p1)/p1
        r1 = (p2-p0)/p0
        return r0,r1
